<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>弹球</title>
    <style>
        body{
            transform: all 1.2s;
        }
        #box {
            position: absolute;
            width: 20px;
            height: 20px;
            background-color: lightskyblue;
            border-radius: 50%;
        }

        #box2 {
            width: 200px;
            height: 20px;
            background-color: lightcoral;
            position: absolute;
            left: 50%;
            bottom: 0px;
        }
    </style>
    <script src="../lib/jquery-3.5.1.js"></script>
</head>

<body>
    <div id="box"></div>
    <div id="box2"></div>
    <script>
        var x = 0; //x轴
        var y = 0; //y轴
        var step = 3;  //步长
        var xbj; //拿到屏幕的宽度
        var ybj;  //拿到屏幕的高度
        var r_bj = false; //是否碰到了边界呢？ right边界
        var t_bj = false; //top边界
        let score = 0;
        start();
        function start() {
            var xbj = window.innerWidth - $("#box").width(); //拿到屏幕的宽度
            var ybj = window.innerHeight - $("#box").height();  //拿到屏幕的高度

            if (x < xbj && r_bj == false) {
                x = x + step;
            } else {
                x = x - step;
                r_bj = true;
                if (x < 0) {
                    r_bj = false;
                }
            }

            if (y < ybj && t_bj == false) {
                y = y + step;
            } else {
                y = y - step;
                t_bj = true;
                if (y < 0) {
                    t_bj = false;
                }
            }

            
            // 碰撞检测
            let box1_x =  $("#box").offset().left;
            let box1_y =  $("#box").offset().top;
            let box2_x = $("#box2").offset().left;
            if( box1_y >= ybj && (box1_x < box2_x || box2_x+200<box1_x)){
                alert("你输了你的分数是"+score);
            }else if(box1_y >= ybj && (box1_x > box2_x || box2_x+200>box1_x)){
                score += 10;
            }
            

            $("#box").css({ "left": x, "top": y });
            setTimeout(() => {
                start();
            }, 8);
        }


        let keyStep = 20;
        $(document).keydown(function (e) {
            let box2_x = $("#box2").offset().left;
            let keyCode = e.which;
            if (keyCode == 39 ) {
                // $("#box2").css("left", (box2_x += keyStep) + "px");
                $("#box2").animate({
                    left:(box2_x += keyStep),
                },31);
            }

            if (keyCode == 37 &&(box2_x -= keyStep)>0) {
                $("#box2").css("left", (box2_x -= keyStep) + "px");
            }

        })
    </script>
</body>

</html>